package es.upv.tricia;

import java.util.ArrayList;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import es.upv.tricia.Tricia.GameQuestions;
import es.upv.tricia.util.HighScoreReader;

public class LocalGame implements Game
{
	private static final String TAG = "LocalGame";

	private ArrayList<GameListener> mListeners = new ArrayList<GameListener>();

	private Context mContext;

	private String mEmail;

	public LocalGame(Context context)
	{
		this.mContext = context;
	}

	@Override
	public void initialize(String email)
	{
		this.mEmail = email;
	}

	@Override
	public void start()
	{
		ContentResolver cr = mContext.getContentResolver();

		cr.insert(GameQuestions.CONTENT_URI, null);

		String[] projection = { "count(*) as count" };
		Cursor cursor = cr.query(GameQuestions.CONTENT_URI, projection, null,
				null, null);

		if (cursor.moveToFirst()) {
			int count = cursor.getInt(0);

			Log.d(TAG, "Found " + count + " questions");

			for (GameListener listener : mListeners) {
				listener.onGameStart(count);
			}
		}

		cursor.close();
	}

	@Override
	public void stop()
	{
		mContext.getContentResolver().delete(GameQuestions.CONTENT_URI, null,
				null);

		for (GameListener listener : mListeners) {
			listener.onGameStop();
		}
	}

	@Override
	public void loadQuestion(int questionNo)
	{
		ContentResolver cr = mContext.getContentResolver();

		String[] projection = { GameQuestions.SUBJECT,
				GameQuestions.QUESTION_TEXT, GameQuestions.ANSWER1,
				GameQuestions.ANSWER2, GameQuestions.ANSWER3,
				GameQuestions.ANSWER4, GameQuestions.RIGHT_ANSWER,
				GameQuestions.HELP };
		String selection = GameQuestions._ID + "=?";
		String[] selectionArgs = new String[] { Integer
				.toString(questionNo + 1) };

		Cursor cursor = cr.query(GameQuestions.CONTENT_URI, projection,
				selection, selectionArgs, null);

		if (cursor.moveToFirst()) {
			Log.d(TAG, "Loaded question " + cursor.getString(1));

			Question question = new Question();
			question.setSubject(cursor.getString(0));
			question.setQuestionText(cursor.getString(1));
			question.setAnswers(new String[] { cursor.getString(2),
					cursor.getString(3), cursor.getString(4),
					cursor.getString(5) });
			question.setRightAnswer(cursor.getInt(6));
			question.setHelp(cursor.getInt(7));

			for (GameListener listener : mListeners) {
				listener.onQuestionLoaded(question);
			}
		}

		cursor.close();
	}

	@Override
	public void publishScore(String username, int score)
	{
		HighScoreList highScoreList = HighScoreReader.loadHighScores(mContext);
		highScoreList.getScores().add(new HighScore(mEmail, username, score));
		HighScoreReader.saveHighScores(mContext, highScoreList);
	}

	@Override
	public void addGameListener(GameListener listener)
	{
		synchronized (mListeners) {
			mListeners.add(listener);
		}
	}

}
